#!/usr/bin/env zx


(async function () {
  $.shell = '/bin/zsh'
  await traverseSubFolder(process.env.it);
  // await traverseSubFolder(process.env.rdc);
  // await traverseSubFolder(process.env.mine);
  // await traverseSubFolder(process.env.open);
})();

async function traverseSubFolder(root) {
  cd(root)
  // await $`pwd`

  let folders = await $`find . -type d -name .git`.then((result) => {
    return result.stdout.trim().split(/\s*\n\s*/).map(p => p.replace(/\.git$/, ''));
  }).catch((err) => { });

  // console.log('folders', folders, path.resolve(root, folders[0]));

  for (let i = 0; i < folders.length; i++) {
    const folder = folders[i];
    await updateAllRepoBranch(path.resolve(root, folder))
  }

  async function updateAllRepoBranch(folder) {
    cd(folder)
    let branchs = await $`git branch`
    branchs = branchs.stdout.trim().split(/\s*\n\s*/).map(name => name.trim());
    // console.log('branchs', branchs);
    for (let i = 0; i < branchs.length; i++) {
      const branch = branchs[i];
      await nothrow(branch.startsWith('*') ? $`git pull` : $`git fetch origin '${branch}':'${branch}'`);
    }
  }
}